package com.kaifamiao.filter;

import org.tinylog.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;

public class CharacterEncodingFilter implements Filter {
    // 用常量约定表示字符编码的初始化参数的名称
    public static final String ENCODING_PARAM_NAME = "encoding";
    // 用常量约定默认的字符编码名称
    public static final String ENCODING_DEFAULT = "UTF-8";

    private String encoding;
    private String name ;

    @Override
    public void init(FilterConfig config) throws ServletException {
        name = config.getFilterName();
        // Logger.trace("初始化" + name + "过滤器");
        Logger.trace( "初始化{}过滤器", name );
        // 获取指定初始化参数的值
        encoding = config.getInitParameter(ENCODING_PARAM_NAME);
        encoding = encoding == null || encoding.isBlank() ? ENCODING_DEFAULT : encoding;
        encoding = Charset.isSupported(encoding) ? encoding : ENCODING_DEFAULT;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        String uri = request.getRequestURI();
        // Logger.trace("过滤器"+ name +"正在过滤" + uri );
        Logger.trace( "过滤器{}正在过滤{}", name, uri);
        // 在向后传递请求和响应之前就设置字符编码
        req.setCharacterEncoding(encoding);
        resp.setCharacterEncoding(encoding);
        // 设置字符编码后再向后传递请求和响应
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
    }

}
